package com.xinyun.client;

import com.xinyun.server.protocol.ProtocolData;
import com.xinyun.server.protocol.ProtocolDataHeader;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * Created by bubusy on 16/5/21.
 */
public class Client {
    public static void main(String[] args) throws Exception {
        String host;
        int port;
        port = 5000;
        host = "localhost";
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            Bootstrap b = new Bootstrap(); // (1)
            b.group(workerGroup); // (2)
            b.channel(NioSocketChannel.class); // (3)
            b.option(ChannelOption.SO_KEEPALIVE, true); // (4)
            b.handler(new ClientInitializer());

            // Start the client.
            ChannelFuture f = b.connect(host, port).sync(); // (5)


            //f.channel().closeFuture().sync();

            f.awaitUninterruptibly();
            if (f.isDone()) {
                System.out.println("connected");

                Channel channel = f.channel();

                //发送boardID
                ProtocolDataHeader header = new ProtocolDataHeader();
                header.setMsgType(1);
                ByteBuf body = channel.alloc().buffer(7);
                body.writeByte(20);
                body.writeByte(16);
                body.writeByte(10);
                body.writeByte(28);
                body.writeByte(10);
                body.writeByte(40);
                body.writeByte(56);
                header.setLength(body.readableBytes());
                ProtocolData pd = new ProtocolData(header, body);
                channel.writeAndFlush(pd);


                //心跳
                new HeartbeatThread(f).run();
            }

            // Wait until the connection is closed.
            f.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
        }
    }
}
